/**
 * 
 */
package com.shine.icis.blo.imp;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.shine.icis.blo.IETLContextVarService;
import com.shine.icis.blo.IETLLogService;
import com.shine.icis.dao.IETLContextVarDAO;
import com.shine.icis.dao.IETLLogDAO;
import com.shine.icis.dao.ISubmitConfDAO;
import com.shine.icis.dto.SubmitCalendar;
import com.shine.icis.exception.ICISException;
import com.shine.icis.hbean.ETLContextVar;
import com.shine.icis.hbean.ETLRunLog;
import com.shine.icis.hbean.ProgExeLog;
import com.shine.icis.ts.client.TaskServerClient;

/**
 * @author zsy
 *
 */
public class ETLContextVarService implements IETLContextVarService {
	
	private IETLContextVarDAO etlContextVarDAO;
	private ISubmitConfDAO submitConfDAO;
	private IETLLogService etlLogService;
	private TaskServerClient taskServerClient;
	private IETLLogDAO etlLogDAO;

	public void setEtlContextVarDAO(IETLContextVarDAO etlContextVarDAO) {
		this.etlContextVarDAO = etlContextVarDAO;
	}
	
	public void setSubmitConfDAO(ISubmitConfDAO submitConfDAO) {
		this.submitConfDAO = submitConfDAO;
	}
	
	public void setEtlLogService(IETLLogService etlLogService) {
		this.etlLogService = etlLogService;
	}
	public void setTaskServerClient(TaskServerClient taskServerClient) {
		this.taskServerClient = taskServerClient;
	}
	
	public void setEtlLogDAO(IETLLogDAO etlLogDAO) {
		this.etlLogDAO = etlLogDAO;
	}
	
	@Override
	public List<ETLContextVar> getAllETLContextVar() {
		return etlContextVarDAO.findAll();
	}

	@Override
	public ETLContextVar getETLContextVarById(String id) {
		if (id == null) {
			return null;
		}
		return etlContextVarDAO.findById(id);
	}

	@Override
	public ETLContextVar getETLContextVarByName(String varName) {
		if (varName == null) {
			return null;
		}
		return etlContextVarDAO.findByName(varName);
	}

	@Override
	public boolean txResubmitConf(String busiDate, boolean loadTr12Flag, String userCode) throws ICISException {
		//单独记一条整个过程开始日志（因为TS开始执行有很长延迟，提前插一条就表示已在运行中）
		etlLogService.ntxAddProgExeLog(ProgExeLog.ETL_TYPE_PRO, null, ETLRunLog.RUN_STATUS_START);
		//记录运行日志
		etlLogService.ntxAddETLRunLog(ProgExeLog.ETL_PROC_ID_EXCRACT, ETLRunLog.PREP_LEVEL_ID_INFO, ETLRunLog.RUN_STATUS_START, "采集数据：设置开始执行参数");
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
		if(busiDate.compareTo(sd.format(new Date())) > 0) {
			throw new ICISException("不能选择今天之后的日期");
		}

		SubmitCalendar sc = submitConfDAO.findSubmitCalendar(Integer.parseInt(busiDate));
		if (sc.getTradeFlag() == 0) {
			throw new ICISException("所选日期为非交易日");
		}
//		ProgressStatus pss =  dataSubmitService.getProgressStatus();
		boolean actived = getTaskServerActived();
//		if (actived && (pss.getDataColStatus() == -1 
//				 || pss.getDataColStatus() == 0
//				 || pss.getDataColStatus() == 2)) {
//			throw new ICISException("任务或TASKSERVER已经处于运行中，请等待！");
//		}
		ETLContextVar var = etlContextVarDAO.findByName("RUNNING");
		if (actived && ("1".equals(var.getVarValue()) || "-1".equals(var.getVarValue())) ) {
			throw new ICISException("任务或TASKSERVER已经处于运行中，请等待！");
		}
		var.setVarValue("-1");//设为等待状态
		etlContextVarDAO.update(var);
		
		var = etlContextVarDAO.findByName("INCREMENT");
		var.setVarValue(Integer.toString(sc.getIncrementFlag()));//设为是否增量
		etlContextVarDAO.update(var);
		var = etlContextVarDAO.findByName("TRADE_FLAG");
		var.setVarValue(Integer.toString(sc.getTradeFlag()));//设为是否交易日
		etlContextVarDAO.update(var);
		
		var = etlContextVarDAO.findByName("BUSI_DATE");
		var.setVarValue(busiDate);//业务日期
		etlContextVarDAO.update(var);
//		var = etlContextVarDAO.findByName("RESUBMIT");
//		var.setVarValue("1");//设为重报
//		etlContextVarDAO.update(var);
		var = etlContextVarDAO.findByName("RUN_NOW");
		var.setVarValue("1");//设为立即运行采集
		etlContextVarDAO.update(var);
		var = etlContextVarDAO.findByName("OPERATOR");
		var.setVarValue(userCode);//操作者
		etlContextVarDAO.update(var);
		var = etlContextVarDAO.findByName("LOAD_TR12");
		var.setVarValue(loadTr12Flag ? "1" : "0");//是否加载A01－A12
		etlContextVarDAO.update(var);
		return actived;
	}
	
	@Override
	public boolean txDataGenerateConf(String userCode) throws ICISException {
		//单独记一条生成数据的开始（因为TS开始执行有很长延迟，提前插一条就表示已在运行中）
		etlLogService.ntxAddProgExeLog(ProgExeLog.ETL_TYPE_JOB, ProgExeLog.ETL_PROC_ID_GENDATA, ETLRunLog.RUN_STATUS_START);
		//记录运行日志
		etlLogService.ntxAddETLRunLog(ProgExeLog.ETL_PROC_ID_GENDATA, ETLRunLog.PREP_LEVEL_ID_INFO, ETLRunLog.RUN_STATUS_START, "生成数据：设置开始执行参数");

		boolean actived = getTaskServerActived();
		ETLContextVar var = etlContextVarDAO.findByName("RUNNING");
		if (actived && ("1".equals(var.getVarValue()) || "-1".equals(var.getVarValue())) ) {
			throw new ICISException("任务或TASKSERVER已经处于运行中，请等待！");
		}
		
		var = etlContextVarDAO.findByName("RUN_NOW");
		var.setVarValue("2");//设为立即运行生成数据
		etlContextVarDAO.update(var);
		var = etlContextVarDAO.findByName("OPERATOR");
		var.setVarValue(userCode);//操作者
		etlContextVarDAO.update(var);
		return actived;
	}

	@Override
	public boolean getTaskServerActived() {
		ETLContextVar var = etlContextVarDAO.findByName("ACTIVE_TIME");
		boolean active = false;
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
		try {
			Date d = sd.parse(var.getVarValue());
			
			Date now = etlLogDAO.findDatabaseDate();
			long min = (now.getTime() - d.getTime()) / 60000;
			if (min <= 6) {//TASKSERVER是5分钟更新一次时间，时间相差5分钟说明TS已出错
				active = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return active;
	}
	
	@Override
	public boolean restartTaskServerEnalble() {
		if (taskServerClient == null) {
			return false;
		}
		return taskServerClient.isEnable();
	}
	
	@Override
	public void txRestartTaskServer() throws Exception {
		if (restartTaskServerEnalble()) {
			ETLContextVar var = etlContextVarDAO.findByName("RUNNING");
			var.setVarValue("-2");//设为初始状态
			etlContextVarDAO.update(var);
			var = etlContextVarDAO.findByName("RUN_NOW");
			var.setVarValue("0");//设为检测到点运行
			etlContextVarDAO.update(var);
			var = etlContextVarDAO.findByName("OPERATOR");
			if (var != null) {
				var.setVarValue("");//操作者设为空
				etlContextVarDAO.update(var);
			}
			taskServerClient.restartTaskServer();
		}
	}

	
}

